﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Web;
using ASPNETPerformance.App_BusinessLogic.Helpers;
using ASPNETPerformance.App_BusinessLogic.Utils;

namespace ASPNETPerformance.App_BusinessLogic.HttpModules {
    public class DiskCacheHttpModule : IHttpModule {
        private ReaderWriterLockSlim cacheLock = new ReaderWriterLockSlim();

        public void Init( HttpApplication application ) {
            application.BeginRequest += ApplicationBeginRequest;
        }

        private void ApplicationBeginRequest( object sender, EventArgs e ) {
            var context = HttpContext.Current;
            var request = context.Request;
            var url = request.RawUrl;


            if ( !url.ToUpperInvariant().EndsWith( "DISKCACHE.ASPX" ) ||
                !CommonHelper.GetCookieBool( "IsEnableDiskCache" ) || !( CommonHelper.GetCookieInt( "DiskCacheTime" ) > 0 ) ) {
                return;
            }

            var response = context.Response;
            var path = GetPath( url );
            var file = new FileInfo( path );

            if ( CommonHelper.GetCookieBool( "IsEnableDiskCacheAndCompression" ) ) {
                ResponseCompressionType compressionType = this.GetCompressionMode( request );
                if ( compressionType != ResponseCompressionType.None ) {
                    response.AppendHeader( "Content-Encoding", compressionType.ToString().ToLower() );
                    if ( compressionType == ResponseCompressionType.GZip ) {
                        response.Filter = new GZipStream( response.Filter, CompressionMode.Compress );
                    }
                    else {
                        response.Filter = new DeflateStream( response.Filter, CompressionMode.Compress );
                    }
                }
            }

            if ( CommonHelper.GetCookieBool( "IsEnableDiskCacheAndOutputCache" ) ) {
                response.Cache.SetExpires( DateTime.Now.AddSeconds( CommonHelper.GetCookieInt( "DiskCacheTime" ) ) );
                response.Cache.SetCacheability( HttpCacheability.Public );
                response.Cache.SetOmitVaryStar( true );
            }

            if ( DateTime.Now.Subtract( file.LastWriteTime ).TotalSeconds < CommonHelper.GetCookieInt( "DiskCacheTime" ) ) {
                response.TransmitFile( path );
                response.End();
                return;
            }

            cacheLock.EnterWriteLock();
            try {
                var stream = file.OpenWrite();
                response.Filter = new CaptureFilter( response.Filter, stream );
            }
            catch ( Exception ) {
                //TODO log this error
                cacheLock.ExitWriteLock();
            }
        }

        public void Dispose() {

        }

        private static string GetPath( string url ) {
            var hash = Hash( url );
            string fold = HttpContext.Current.Server.MapPath( "~/Temp/" );
            return string.Concat( fold, hash );
        }

        private static string Hash( string url ) {
            url = url.ToUpperInvariant();
            var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
            var bs = md5.ComputeHash( Encoding.ASCII.GetBytes( url ) );
            var s = new StringBuilder();
            foreach ( var b in bs ) {
                s.Append( b.ToString( "x2" ).ToLower() );
            }
            return s.ToString();
        }

        private ResponseCompressionType GetCompressionMode( HttpRequest request ) {
            string acceptEncoding = request.Headers[ "Accept-Encoding" ];
            if ( string.IsNullOrEmpty( acceptEncoding ) )
                return ResponseCompressionType.None;

            acceptEncoding = acceptEncoding.ToUpperInvariant();

            if ( acceptEncoding.Contains( "GZIP" ) )
                return ResponseCompressionType.GZip;
            else if ( acceptEncoding.Contains( "DEFLATE" ) )
                return ResponseCompressionType.Deflate;
            else
                return ResponseCompressionType.None;
        }

        private enum ResponseCompressionType {
            None,
            GZip,
            Deflate
        }
    }

    public class CaptureFilter : Stream {
        private readonly Stream _responseStream;
        private readonly FileStream _cacheStream;

        public override bool CanRead {
            get {
                return false;
            }
        }
        public override bool CanSeek {
            get {
                return false;
            }
        }
        public override bool CanWrite {
            get {
                return _responseStream.CanWrite;
            }
        }
        public override long Length {
            get {
                throw new NotSupportedException();
            }
        }
        public override long Position {
            get {
                throw new NotSupportedException();
            }
            set {
                throw new NotSupportedException();
            }
        }

        public CaptureFilter( Stream responseStream, FileStream stream ) {
            _responseStream = responseStream;
            _cacheStream = stream;
        }

        public override long Seek( long offset, SeekOrigin origin ) {
            throw new NotSupportedException();
        }
        public override void SetLength( long length ) {
            throw new NotSupportedException();
        }
        public override int Read( byte[] buffer, int offset, int count ) {
            throw new NotSupportedException();
        }
        public override void Flush() {
            _responseStream.Flush();
            _cacheStream.Flush();
        }
        public override void Write( byte[] buffer, int offset, int count ) {
            _cacheStream.Write( buffer, offset, count );
            _responseStream.Write( buffer, offset, count );
        }

        public override void Close() {
            _responseStream.Close();
            _cacheStream.Close();
        }
        protected override void Dispose( bool disposing ) {
            if ( disposing ) {
                _responseStream.Dispose();
                _cacheStream.Dispose();
            }
        }
    }
}
